package com.bojx.cms.interceptor;

import java.util.List;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log4jLog;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.render.JsonRender;


public class AuthInterceptor implements Interceptor{
	private static final Log4jLog LOG=Log4jLog.getLog(AuthInterceptor.class);
	@Override
	public void intercept(Invocation inv) {
		Controller ctr=inv.getController();
		try{
			
			String username=ctr.getCookie("username");
			String action=inv.getActionKey();
			Long permId=Db.queryLong("select id from cms_perm where action=?",action);
			if(permId==null){
				inv.invoke();
				return;
			}
			List<String> permIds=CacheKit.get("UserCachingFilter", username+"perms");
			if(permIds==null){
				throw new Exception("请重新登录");
			}
			for(String id:permIds){
				if(Long.valueOf(id)==permId){
					inv.invoke();
					return;
				}
			}
			Record result=new Record();
			result.set("code", "12");
			result.set("message","对不起您没有权限");
			ctr.render(new JsonRender(result).forIE());
		}catch(Exception e){
			LOG.error(e.getMessage(),e);
			Record result=new Record();
			result.set("code", "12");
			result.set("message",e.getMessage());
			ctr.render(new JsonRender(result).forIE());
		}
		
		
	}

}
